﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using Storytelling.Entidades;

namespace Storytelling.Utils
{
    internal static class ModelExtensions
    {
        public static void CarregarArray<T, TItem>(this T obj, ref string[] array, Expression<Func<T, ICollection<TItem>>> expression, Func<TItem, Nomeado> funcItem)
        {
            string nome = ((MemberExpression)expression.Body).Member.Name;
            PropertyInfo propertyInfo = typeof(T).GetProperty(nome);
            var cole = propertyInfo.GetValue(obj, null);

            if (cole != null)
            {
                ICollection<TItem> coleItem = (ICollection<TItem>)cole;
                array = array ?? new string[coleItem.Count];
                int i = 0;
                foreach (var item in coleItem)
                {
                    Nomeado nomeado = funcItem(item);
                    if (nomeado != null && !string.IsNullOrEmpty(nomeado.Nome))
                    {
                        array[i] = nomeado.Nome;
                    }
                    i++;
                }
            }
        }

        public static void Transferidor<T, TItem, TArray>(this T obj, TArray[] array, Expression<Func<T, ICollection<TItem>>> expression, Action<TArray, TItem> actionItem)
        {
            string nome = ((MemberExpression)expression.Body).Member.Name;
            PropertyInfo propertyInfo = typeof(T).GetProperty(nome);
            var cole = propertyInfo.GetValue(obj, null);

            if (cole != null)
            {
                int i = 0;
                foreach (var item in ((ICollection<TItem>)cole))
                {
                    if (i < array.Length)
                    {
                        actionItem(array[i], item); 
                    }
                    else
                    {
                        actionItem(default(TArray), item); 
                    }
                    i++;
                }
            }
            else
            {
                ICollection<TItem> list = new List<TItem>();
                for (int i = 0; i < array.Length - 1; i++)
                {
                    var item = Activator.CreateInstance<TItem>();
                    actionItem(array[i], item);
                    list.Add(item);
                }
                propertyInfo.SetValue(obj, list, null);
            }
        }
    }
}
